<template>
  <div class="user-logout-container">
    <el-popconfirm
      title="确定要退出登录吗？"
      confirm-button-text="确定"
      cancel-button-text="取消"
      @confirm="handleLogout"
    >
      <template #reference>
        <el-button type="text" class="logout-btn">
          <span v-if="!loading">退出登录</span>
          <span v-else>退出中...</span>
        </el-button>
      </template>
    </el-popconfirm>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { logoutApi } from '@/api/user'

const router = useRouter()
const loading = ref(false)

// 模拟API调用
const logoutApi = async () => {
  // 这里替换为实际的API调用
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ code: 0, data: true, message: 'ok' })
    }, 800)
  })
}

const handleLogout = async () => {
  try {
    loading.value = true
    
    // 调用注销接口
    const res = await logoutApi()
    
    if (res.code === 0) {
      ElMessage.success('退出登录成功')
      
      // 清除本地token等认证信息
      localStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
      
      // 跳转到登录页
      router.push('/login')
    } else {
      ElMessage.error(res.message || '退出登录失败')
    }
  } catch (error) {
    console.error('注销出错:', error)
    ElMessage.error('请求出错，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.user-logout-container {
  display: inline-block;
}

.logout-btn {
  color: var(--el-color-danger);
  padding: 0;
  font-size: 14px;
}

.logout-btn:hover {
  color: var(--el-color-danger-light-3);
}
</style>